package com.example.androidgeneric;

import java.util.List;

import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class MyLocation implements LocationListener {

	private Context context;
	
	private LocationManager lm;
	private String provider;
	public onLocation mlocation;
	
	private double Latitude, Longitude;
	
	public interface onLocation {
		public void getLocationPosition(double lat, double lng);
		public void notFoundProvider();
	}
	
	public MyLocation(Context context) {
		this.context = context;
		setLocationManager();
	}
	
	private void setLocationManager() {
		lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		
		Criteria c = new Criteria();
		provider = lm.getBestProvider(c, true);
		
		if (provider == null || !lm.isProviderEnabled(provider)) {
			List<String> list = lm.getAllProviders();
			
			for (int i = 0; i < list.size(); i++) {
				String temp = list.get(i);
				
				if (lm.isProviderEnabled(temp)) {
					provider = temp;
					break;
				}
			}
		}
		
		Location location = lm.getLastKnownLocation(provider);
		
		Latitude = location.getLatitude();
		Longitude = location.getLongitude();
		
		if (location == null) {
			mlocation.notFoundProvider();
		} else {
			onLocationChanged(location);
		}
	}
	
	public void setOnLocation(onLocation mLocation) {
		this.mlocation = mLocation;
	}

	@Override
	public void onLocationChanged(Location location) {
		Latitude = location.getLatitude();
		Longitude = location.getLongitude();
		mlocation.getLocationPosition(Latitude, Longitude);
	}

	@Override
	public void onProviderDisabled(String arg0) {
		
	}

	@Override
	public void onProviderEnabled(String arg0) {
		
	}

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		
	}

}
